#include <iostream>


using namespace std;



void printTable();
void initTable();
bool add(int,int);
bool isFullTable();
bool isFinished();
bool checkHorizon(int,int);
bool checkVertical(int,int);
bool checkDiagonal(int,int);

int table[6][7];//={{1,2,1,2,1,2,0},{1,1,1,2,1,2,0},{1,2,1,2,1,2,0},{0,0,0,0,0,0,0},{0,0,0,0,0,0,0},{0,0,0,0,0,0,0}};


int main (int argc, char * const argv[]) {
	initTable();
	int pick;
	int player=1;
	do
	{
		cout<< "pick column 0-6:";
		cin >> pick;
		if(add(pick,player))
		{
			if(player==1)
				player=2;
			else
				player=1;
		}
	    printTable();
	}while(!isFullTable() && !isFinished());
    return 0;
}

bool add(int col,int team)
{
	int i;
	if(col<0 || col>6)
		return false;
	for(i=0;i<6;i++)
	{
		if(table[i][col]==0)
			break;
	}
	if(i!=6)
	{
		table[i][col]=team;
		return true;
	}
	else
		return false;
}
void initTable()
{
	for (int i=0;i<6;i++)
	{
		for(int j=0;j<7;j++)
		{
			table[i][j]=0;
		}
	}
}
void printTable()
{
	char symbol;
	for (int i=5;i>-1;i--)
	{
		for(int j=0;j<7;j++)
		{
			
			switch(table[i][j])
			{
				case 0:
					symbol = ' ';
					break;
				case 1:
					symbol = 'X';
					break;
				case 2:
					symbol = 'O';
					break;
				default:
					symbol = '?';
					break;
			}
			cout <<symbol;
		}
		cout << endl;
	}
}

bool isFullTable()
{
	for (int i=0;i<6;i++)
	{
		for(int j=0;j<7;j++)
		{
			if(table[i][j]==0)
				return false;
		}
	}
	return true;
}

bool isFinished()
{
	for(int i=0;i<6;i++)
	{
		for(int j=0;j<7;j++)
		{
			int target = table[i][j];
			if(target!=0)
			{
				if(checkHorizon(i,target) || checkVertical(j,target) || checkDiagonal(i,j))
				{
					cout << "FINISHED" << endl;
					return true;
				}
			}
		}
	}
	return false;
}

bool checkHorizon(int i,int value)
{
	int count=0;
	for(int j=0;j<7;j++)
	{
		if(table[i][j]==value)
		{
			count++;
			if(count>3)
				return true;
		}
		else
			count=0;
	}
	return false;
}
bool checkVertical(int j,int value)
{
	int count=0;
	for(int i=0;j<6;j++)
	{
		if(table[i][j]==value)
		{
			count++;
			if(count>3)
				return true;
		}
		else
			count=0;
	}
	return false;
}
bool checkDiagonal(int i,int j)
{
	int tempi=i,tempj=j;
	int value = table[i][j];
	int count = 0;
	
	//** FROM BOTTOM-LEFT TO UPPER-RIGHT **//
	while(i>-1 && j>-1)
	{
		i--;
		j--;
	} 
	
	while(i<6 && j<7)
	{
		if(table[i][j]==value)
		{
			count++;
			if(count>3)
				return true;
		}
		else
			count=0;
		i++;
		j++;
	}
	
	i= tempi;
	j= tempj;
	count = 0;
	//** FROM UPPER-LEFT TO BOTTOM-RIGHT **//
	while(i<6 && j>-1)
	{
		i++;
		j--;
	} 
	
	while(i>-1 && j<7)
	{
		if(table[i][j]==value)
		{
			count++;
			if(count>3)
				return true;
		}
		else
			count=0;
		i--;
		j++;
	}
	return false;
}
